#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CC FTP 服务器
Usage:
    python ftp_server.py  [-p 2121] [-u user] [-P 12345] [-d ./ftp_root]
    Example: ftp://user:12345@your-server-ip:21
"""
# 打包exe命令 pyinstaller -F ftp_server.py

import os
import time
import argparse
import logging
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

VERSION = "Version 1.0"
DEFAULT_PORT = 21
DEFAULT_ROOT = os.path.join(os.getcwd(), "ftp_root")

def main():
    ap = argparse.ArgumentParser(description=f"CC FTP Server {VERSION}")
    ap.add_argument("-p", "--port", type=int, default=DEFAULT_PORT, help="listen port")
    ap.add_argument("-u", "--user", default="user", help="username")
    ap.add_argument("-P", "--password", default="12345", help="password")
    ap.add_argument("-d", "--directory", default=DEFAULT_ROOT, help="root directory for anonymous/user")
    args = ap.parse_args()

    # 1. 创建根目录
    os.makedirs(args.directory, exist_ok=True)

    # 2. 用户授权
    auth = DummyAuthorizer()
    # 用户 home 目录就是指定目录，权限 = 读写删除创建重命名
    auth.add_user(args.user, args.password, args.directory, perm="elradfmwMT")
    # 匿名只读（不需要可注释）
    auth.add_anonymous(args.directory, perm="elradfmwMT")

    # 3. 处理器
    handler = FTPHandler
    handler.authorizer = auth
    handler.banner = "pyftpdlib based mini FTP server ready."
    
    # Configure passive mode to prevent connection issues
    handler.passive_ports = range(60000, 65535)
    
    # Set timeouts to prevent premature disconnections
    handler.timeout = 600  # 10 minutes
    handler.dtp_handler_timeout = 300  # 5 minutes
    
    # 4. 启动
    address = ("0.0.0.0", args.port)
    server = FTPServer(address, handler)
    server.max_cons = 128
    server.max_cons_per_ip = 10
    
    # Add server timeout configuration
    server.handler.timeout = 600
    
    print(f"[*] FTP server listening on ftp://0.0.0.0:{args.port}")
    print(f"[*] user={args.user}  password={args.password}")
    print(f"[*] root directory: {args.directory}")
    print(f"[*] passive ports range: 60000-65534")
    
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print("\n[!] Shutting down FTP server ...")
        server.close_all()
    except Exception as e:
        print(f"\n[!] Server error: {e}")
        server.close_all()

if __name__ == "__main__":
    # Enable logging for debugging connection issues
    logging.basicConfig(level=logging.INFO)
    while True:
        main()
        time.sleep(10)